package com.chpc.edeal.dao.impl;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.chpc.edeal.dao.CategoryDao;
import com.chpc.edeal.model.Category;
import com.chpc.edeal.model.Image;

@Repository
public class CategoryDaoImpl implements CategoryDao {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Value("/resources/categorys")
	private Resource template;
	
	@Autowired
	public CategoryDaoImpl(SessionFactory sessionFactory){
		this.sessionFactory=sessionFactory;
	}
	
	@Transactional
	public boolean addCategory(com.chpc.edeal.vo.Category categoryVo) {
		
		Category c=new Category();
		c.setName(categoryVo.getName());
		c.setDescription(categoryVo.getDescription());
		Image i=new Image();
		i.setCaption(categoryVo.getName());
		i.setUploadedDate(new Timestamp( new java.util.Date().getTime()));
	String imageFilename=categoryVo.getImage().getOriginalFilename();
	
	String fileExtension=null;
	imageFilename="chpc.jpg";
	String a[]=imageFilename.split("\\.");
	if(a!=null&&a.length>0){
    fileExtension=a[a.length-1];
	}
	String destinationFilename=categoryVo.getName()+"."+fileExtension;
		i.setUrl("resources/categorys/"+destinationFilename);
		System.out.println(i.getUrl());
		try {
			System.err.println(template.getURL());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			categoryVo.getImage().transferTo(new File(template.getFile(), destinationFilename));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		c.setImage(i);
	
		sessionFactory.getCurrentSession().save(c);
		
		
		return true;
	}
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Resource getTemplate() {
		return template;
	}

	public void setTemplate(Resource template) {
		this.template = template;
	}

	@Transactional
	public Set<Category> getCategorys() {
		// TODO Auto-generated method stub
		return null;
	}
	@Transactional
	public Category getCategory(int id) {
		// TODO Auto-generated method stub
		return null;
	}

}
